package com.robot.orders.controller;

import com.alibaba.fastjson.JSON;
import com.robot.orders.client.*;
import com.robot.orders.pojo.Orders;
import com.robot.orders.pojo.client.Member;
import com.robot.orders.pojo.client.Store;
import com.robot.orders.service.OrdersDetailsService;
import com.robot.orders.service.OrdersService;
import com.robot.orders.service.PurchaseService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * orders控制器层
 * 用于支付
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersDetailsService ordersDetailsService;
    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private MemberClient memberClient;
    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private CouponClient couponClient;
    @Autowired
    private AgentClient agentClient;
    @Autowired
    private CartDetailsClient cartDetailsClient;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String ordersUseCoupon = "1";

    /**
     * 10码豆等于1块钱
     */
    @Value("${sys.orders.beansToPriceRate}")
    private int beansToPriceRate;
    /**
     * 1金豆等于1块钱
     */
    @Value("${sys.orders.goldenBeanToPriceRate}")
    private int goldenBeanToPriceRate;
    /**
     * 城市合伙人收益,指一次交易中城市合伙人获取的收益=总收益*40%
     */
    @Value("${sys.orders.agentRevenueRate}")
    private Double agentRevenueRate;
    /**
     * 手续费/提现的费率=小票金额*0.006
     */
    @Value("${sys.orders.feeRate}")
    private Double feeRate;
    /**
     * 会长收益费率
     */
    @Value("${sys.orders.presidentRate}")
    private Double presidentRate;
    /**
     * 付了一块钱->会员
     */
    @Value("${sys.member.vip1}")
    private String vip1;
    /**
     * 付了198->plus会员
     */
    @Value("${sys.member.vip2}")
    private String vip2;


    /**
     * 这个接口供扫码支付,给前端准备一个订单
     *
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "offline/preOrders/{storeId}", method = RequestMethod.POST)
    public Result addOrdersStepOne(@PathVariable String storeId) throws ParseException {
        Claims claims = getMember();
        if (claims == null) {
            logger.info("claims is null");
            return new Result(StatusCode.ERROR_TOKEN_INVALID);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Member memberInDb = JSON.parseObject(memberClient.thirdFindEnableMemberById(claims.getId()), Member.class);
        logger.info("memberInDb=" + memberInDb);
        if (memberInDb == null) {
            logger.info("member can not found");
            return new Result(StatusCode.ERROR_USER_INVALID);
        }

        //下单时判断店铺是否可用 在查找店铺的是就带条件，这样就不要判断了
        Store storeInDb = JSON.parseObject(merchantClient.findEnableStoreById(storeId), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            logger.info("store can not found");
            return new Result(StatusCode.ERROR_STORE_DOES_NOTE_EXIST);
        }

        HashMap<String, Object> resultMap = new HashMap<String, Object>(3);
        resultMap.put("member", memberInDb);
        resultMap.put("store", storeInDb);
        resultMap.put("ordersId", idWorker.nextId() + "");
        logger.info("resultMap=" + resultMap);
        return new Result(StatusCode.SUCCESS, resultMap);
    }


    @RequestMapping(value = "buyVip/{payAmount}", method = RequestMethod.GET)
    public Result buyPlus(@PathVariable String payAmount) {
        Claims claims = getMember();
        if (claims == null) {
            logger.info("claims is null");
            return new Result(StatusCode.ERROR_TOKEN_INVALID);
        }
        //下单时判断会员是否可用
        Member memberInDb = JSON.parseObject(memberClient.thirdFindEnableMemberById(claims.getId()), Member.class);
        logger.info("memberInDb=" + memberInDb);
        if (memberInDb == null) {
            logger.info("member can not found");
            return new Result(StatusCode.ERROR_USER_INVALID);
        }

        HashMap<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("memberId", memberInDb.getId());
        resultMap.put("memberIsPlus", memberInDb.getIsPlus());
        resultMap.put("ordersId", idWorker.nextId() + "");
        resultMap.put("memberOpenId", memberInDb.getOpenId());
        logger.info("resultMap=" + resultMap);
        return new Result(StatusCode.SUCCESS, resultMap);

    }


    /**
     * 添加测试用的新增会员提醒假数据
     *
     * @param agentIdOrStoreId
     * @param memberId
     * @return
     */
    @RequestMapping(value = "test/{agentIdOrStoreId}/{memberId}", method = RequestMethod.GET)
    public Result addMembersData(@PathVariable String agentIdOrStoreId, @PathVariable String memberId) {
        /**
         * 增加agentMember
         * 向缓存中放一份用于agent端会员提醒
         */
        String agentMemberKey = "agentMember_";
        List<Object> agentMemberList = new ArrayList<>();
        agentMemberList.add(memberId);
        redisTemplate.opsForList().leftPush(agentMemberKey + agentIdOrStoreId, agentMemberList);
        logger.info("add agentMember=" + agentMemberList);

        /**增加merchantMember
         * 向缓存中放一份用于agent端会员提醒
         */
        String merchantMemberKey = "merchantMember_";
        List<Object> merchantMemberList = new ArrayList<>();
        merchantMemberList.add(memberId);
        redisTemplate.opsForList().leftPush(merchantMemberKey + agentIdOrStoreId, merchantMemberList);
        logger.info("add merchantMember=" + merchantMemberList);
        return new Result(StatusCode.SUCCESS, "新增会员id=" + memberId);
    }



    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, ordersService.findAll());
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Orders> pageList = ordersService.findSearch(searchMap, page, size);
        logger.info("pageList");
        logger.info(pageList.toString());
        logger.info("pageList");

        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, ordersService.findSearch(searchMap));
    }

    /**
     * 修改
     *
     * @param orders
     */
    @RequestMapping(value = "admin/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody Orders orders, @PathVariable String id) {
        orders.setId(id);
        ordersService.update(orders);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        ordersService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    private Claims getMember() {
        return (Claims) request.getAttribute("robot_member");
    }




}
